package Model;

import com.twu.biblioteca.KeyboardUserInput;
import com.twu.biblioteca.Message;

import java.util.ArrayList;

public class Session {

    private User user;

    private ArrayList<User> userList;
    private boolean hasUserLoggedIn;
    private KeyboardUserInput keyInput;

    public Session(ArrayList<User> userList){
        this.userList = userList;
        hasUserLoggedIn = false;
        keyInput = new KeyboardUserInput();
    }

    public boolean isUserLoggedIn() {
        if(!hasUserLoggedIn){
            LoginCredential loginCredential;
            if ((loginCredential = userLoginPrompt())==null)
            {
                Message.printInvalidUserName();
                return false;
            }

            if(!checkIfCredentialsCorrect(loginCredential)){
                Message.printInvalidUserNameAndPass();
                return false;
            }
            else{
                hasUserLoggedIn = true;
                return true;
            }

        }
        else
            return true;
    }

    public User getUser(){
        return this.user;
    }

    private boolean checkIfCredentialsCorrect(LoginCredential userInputCredentials) {
        LoginCredential current;
        for(User user: this.userList){
            current = user.getLoginCredentials();
            if(current.equals(userInputCredentials)){
                this.user = user;
                return true;
            }
        }
        return false;
    }



    private LoginCredential userLoginPrompt() {
        System.out.print("Enter Username: ");
        String usernameString = keyInput.getInput();
        int username = LoginCredential.sanitizedUsernameCheck(usernameString);
        System.out.print("Enter Password: ");
        String password = keyInput.getInput();

        if(username != -1){
            return new LoginCredential(username, password);
        }
        else {
            return null;
        }

    }

}
